<template>
  <a-card title="部门管理" class="general-card" :bordered="false">
    <a-row class="action">
      <a-switch v-model="strict">
        <template #checked> 级联</template>
        <template #unchecked>单选</template>
      </a-switch>
      <a-button @click="addRoot">添加部门</a-button>
      <a-button @click="addSubdivision">添加子部门</a-button>
      <a-button @click="delAll">批量删除</a-button>
      <a-button @click="getParentList">刷新</a-button>
    </a-row>
    <a-row style="margin: 16px 0">
      <a-col :span="8">
        <a-alert type="warning"
          >当前选择编辑：
          <span>{{ editTitle }}</span>
        
        </a-alert>
        <div class="tree-bar" :style="{ maxHeight: maxHeight }">
          <a-tree
            v-model:checked-keys="checkedKeys"
            :check-strictly="!strict"
            block-node
            :data="treeData"
            :checkable="true"
            @select="handleCateChange"
            @check="handleCheckChange"
          />
        </div>
      </a-col>
      <a-col :span="16">
        <a-form
          :model="form"
          :style="{ width: '600px' }"
        >
          <a-form-item
            field="title"
            tooltip="Please enter username"
            label="部门名称"
          >
            <a-input v-model="form.title" placeholder="请输入部门名称" />
          </a-form-item>
          <a-form-item field="isRead" label="选择角色">
            <a-select v-model="selectedRole" placeholder="选择角色" multiple>
              <a-option v-for="item in users" :key="item.id" :value="item.id">{{
                item.name
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="sortOrder" label="排序值" :rules="[REQUIRED]">
            <a-tooltip content="值越小越靠前，支持小数" position="rt">
              <a-input-number
                v-model="form.sortOrder"
                :style="{ width: '320px' }"
                class="input-demo"
                :min="0"
                :max="1000"
              />
            </a-tooltip>
          </a-form-item>
          <a-form-item>
            <a-button
              html-type="submit"
              style="margin-right: 5px"
              type="primary"
              @click="submitEdit"
              >修改并保存</a-button
            >
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
    <a-modal
      v-model:visible="modalVisible"
      :align-center="false"
      @ok="handleConfirm"
      @cancel="handleClose"
    >
      <template #title>
        {{ modalTitle }}
      </template>
      <a-form
        ref="formRef"
        :model="formAdd"
        layout="horizontal"
        auto-label-width
      >
        <div v-if="showParent">
          <a-form-item label="上级部门：">
            {{ form.title }}
          </a-form-item></div
        >
        <a-form-item field="title" label="部门名称" :rules="[REQUIRED]">
          <a-input v-model="formAdd.title" />
        </a-form-item>
        <a-form-item field="sortOrder" label="排序值" :rules="[REQUIRED]">
          <a-tooltip content="值越小越靠前，支持小数" position="rt">
            <a-input-number
              v-model="formAdd.sortOrder"
              :style="{ width: '320px' }"
              class="input-demo"
              :min="0"
              :max="1000"
            />
          </a-tooltip>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import {
    initDepartment,
    getRoleList,
    addDepartment,
    deleteDepartment,
    getUserByDepartmentId,
    editDepartment,
    updateDepartmentRole,
  } from '@/api/shops';
  import { ref, onMounted, reactive } from 'vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { Message } from '@arco-design/web-vue';
  import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';

  const modal = useCurrentInstance().globalProperties?.$modal; // 获取modal
  const maxHeight = ref(); // 最大高度
  const users = ref<Array<any>>([]); // 角色列表
  const strict = ref(true); // 级联还是单选
  const modalTitle = ref(''); // 模态框标题
  const showParent = ref(false); // 是否展示父级
  const modalVisible = ref(false); // modal显隐
  const formAdd = ref<any>({}); // 新增部门表单
  const selectList = ref<any>(); // 已选列表
  const checkedKeys = ref([]);
  const editTitle = ref(''); // 编辑标题
  const selectedRole = ref([]); // 选择得角色
  const form = ref<any>({
    id: '',
    title: '',
    sortOrder: '',
    isRead: false,
  });
  const treeData = ref();
  const treeDataDefault = ref();
  const formRef = ref();


  
  // 获取部门列表
  const getParentList = () => {
    initDepartment().then((res) => {
      if (res.data.success) {
        treeData.value = res.data.result;
      }
    });
  };
  // 添加一级部门
  const addRoot = () => {
    modalTitle.value = '添加一级部门';
    showParent.value = false;
    formAdd.value = {
      parentId: 0,
      sortOrder: 0,
      status: 0,
    };
    modalVisible.value = true;
  };
  // 添加子部门
  const addSubdivision = () => {
    if (form.value.id == '' || form.value.id == null) {
      Message.warning('请先点击选择一个部门');
      return;
    }
    modalTitle.value = '添加子部门';
    showParent.value = true;
    formAdd.value = {
      parentId: form.value.id,
      sortOrder: 0,
      status: 0,
    };
    modalVisible.value = true;
  };
  const init = () => {
    getParentList();
  };
  // 选择分类回调（点击树节点时触发）
  const handleCateChange = (selectedKeys: any, data: any) => {
    editTitle.value = data.node.title;
    getUserByDepartmentId(data.node.id).then((res) => {
      const way = [] as any;
      res.data.result &&
        res.data.result.forEach((item: any) => {
          way.push(item.roleId);
        });
      selectedRole.value = way;
    });
    getRoleList({ pageNumber: 1, pageSize: 10000 }).then((res) => {
      if (res.data.success) {
        users.value = res.data.result.records;
        form.value = data.node;
        // console.log(users.value,'角色列表')
      }
    });
  };
  // 部门选择事件
  const handleCheckChange = (newCheckedKeys: any, event: any) => {
    selectList.value.push(event.node);
  };
  // 确认添加部门
  const handleConfirm = () => {
    addDepartment(formAdd.value).then((res) => {
      if (res.data.success) {
        Message.success('添加成功');
        modalVisible.value = false;
        init();
      }
    });
  };
  // 取消添加部门
  const handleClose = () => {
    modalVisible.value = false;
  };
  // 批量删除
  const delAll = () => {
    // console.log(checkedKeys.value.length, 'checkedKeys', checkedKeys);
    if (checkedKeys.value.length <= 0) {
      Message.warning('您还未勾选要删除的数据');
      return;
    }
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除所选的${checkedKeys.value.length}条数据及其下级所有数据?`,
      alignCenter: false,
      onOk: async () => {
        let ids = '';
        selectList.value.forEach((item: any) => {
          ids += `${item.id},`;
        });
        const joinid = ids.substring(0, ids.length - 1);
        const res = await deleteDepartment(joinid);
        if (res.data.success) {
          selectList.value = [];
          Message.success('删除成功');
          init();
          formAdd.value = {};
          form.value = {id: '', title: '', sortOrder: '', isRead: false,};
          editTitle.value = '';
        }
      },
    });
  };
  
  // 提交表单
  const submitEdit = () => {
    if (!form.value.id) {
      Message.warning('请先点击选择要修改的部门');
      return;
    }
    const roleWay = [] as any;
    selectedRole.value.forEach((item) => {
      const role = {
        departmentId: form.value.id,
        roleId: item,
      };
      roleWay.push(role);
    });
    Promise.all([
      editDepartment(form.value.id, form.value),
      updateDepartmentRole(form.value.id, roleWay),
    ]).then((res) => {
      console.log(res, 'resssssssssdatatt````');
      if (res[0].data.success) {
        Message.success('编辑成功');
        init();
      }
    });
  };
  // 初始化
  onMounted(() => {
    // 计算高度
    const height = document.documentElement.clientHeight;
    maxHeight.value = `${Number(height - 287)}px`;
    getParentList();
  });
</script>

<style scoped lang="less">
  .action {
    .arco-btn {
      margin-left: 10px;
    }
  }
  .tree-bar {
    overflow: auto;
    margin-top: 5px;
    position: relative;
    min-height: 80px;
  }

  .tree-bar::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  .tree-bar::-webkit-scrollbar-thumb {
    border-radius: 4px;
    -webkit-box-shadow: inset 0 0 2px #d1d1d1;
    background: #e4e4e4;
  }
</style>
